import subprocess


def set_network_metric_by_name(network_name:str, metric:int):
    '''
    设置网卡优先级 按名称
    :param network_name:
    :param metric:
    :return:
    '''
    result = subprocess.run(['netsh', 'interface', 'ipv4', 'set', 'interface', network_name, 'metric=', str(metric)],
                            capture_output=True, text=True)
    # print(result.stdout)
    if "确定" in result.stdout:
        return True
    else:
        return False

def set_network_metric_by_index(index:int, metric:int):
    '''
    设置网卡优先级 按序号
    :param index:
    :param metric:
    :return:
    '''
    if index < 0:
        return False
    network_name_list = get_interface_list()
    if index >= len(network_name_list):
        return False
    network_name = network_name_list[index]
    set_network_metric_by_name(network_name,metric)

def get_interface_list():
    '''
    获取网卡信息表
    :return:
    '''
    'netsh interface ip show config'
    result = subprocess.run(['netsh', 'interface', 'ip', 'show', 'config'], capture_output=True, text=True)
    _stdout = result.stdout
    interfaces = _stdout.split("\n\n")
    interface_list = []
    for interface in interfaces:
        if interface and interfaces != "\n":
            info_rows = interface.split("\n")
            info = {}
            for i in range(len(info_rows)):
                # print(info_rows[i])
                if '接口 "' in info_rows[i] and "的配置" in info_rows[i]:
                    info["interface_name"] = info_rows[i].split('"')[1]
                if "IP 地址" in info_rows[i]:
                    items = info_rows[i].split(" ")
                    info["ip"] = items[len(items) - 1]
                if "默认网关" in info_rows[i]:
                    items = info_rows[i].split(" ")
                    info["default_gateway"] = items[len(items) - 1]
                if "网关跃点数" in info_rows[i]:
                    items = info_rows[i].split(" ")
                    info["gateway_hop_poits"] = int(items[len(items) - 1])
                if "InterfaceMetric" in info_rows[i]:
                    items = info_rows[i].split(" ")
                    info["interface_metric"] = int(items[len(items) - 1])

            if "interface_name" in info.keys() and info["interface_name"] != "Loopback Pseudo-Interface 1":
                interface_list.append(info)
    return interface_list

def auto_loop_change_newwork():
    '''
    自动按顺序切换网卡
    :return:
    '''
    network_name_list = get_interface_list()
    last_index = 0
    for i in range(len(network_name_list)):
        if network_name_list[i]["interface_metric"] == 9999:
            last_index = i + 1
            set_network_metric_by_name(network_name_list[i]["interface_name"], i + 1)
            break
    if last_index >= len(network_name_list):
        last_index = 0
    set_network_metric_by_name(network_name_list[last_index]["interface_name"], 9999)
    return last_index

from threading import Thread
import time

class MainThread(Thread):
    def __init__(self,sleep = 10):
        super().__init__()
        self.sleep = sleep
    def run(self):
        while True:
            try:
                auto_loop_change_newwork()
                print(F"切换IP成功")

            except Exception as E:
                print(F"切换IP异常：{E}")
            time.sleep(self.sleep)

def main(sleep):
    th = MainThread(sleep=sleep)
    th.start()
    th.join()

if __name__ == '__main__':
    import sys
    a = sys.argv
    if len(a) > 1:
        try:
            sleep = int(a[1])
        except:
            sleep = 10
    else:
        sleep = 10
    main(sleep)
